package com.sxfq.loansupermarket.backsystem.modular.analysis.controller;

import java.io.BufferedOutputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.baomidou.mybatisplus.plugins.Page;
import com.sxfq.loansupermarket.backsystem.common.constant.factory.PageFactory;
import com.sxfq.loansupermarket.backsystem.common.controller.BaseController;
import com.sxfq.loansupermarket.backsystem.core.util.StringUtil;
import com.sxfq.loansupermarket.backsystem.modular.analysis.entity.CountData;
import com.sxfq.loansupermarket.backsystem.modular.analysis.entity.PageHomeCount;
import com.sxfq.loansupermarket.backsystem.modular.analysis.entity.PlatFormCount;
import com.sxfq.loansupermarket.backsystem.modular.analysis.entity.RegisterCount;
import com.sxfq.loansupermarket.backsystem.modular.analysis.service.ICountServiceTwo;

/**
 * @author gaofucheng:
 * @version 2017年8月24日 上午9:55:45 数据统计控制器
 */
@SuppressWarnings("unused")
@Controller
@RequestMapping("/dataCount")
public class CountControllerTwo extends BaseController {
	@Autowired
	private ICountServiceTwo countServiceTwo;

	private String PREFIX = "/analysis/count/";

	/**
	 * 数据统计页面跳转
	 * 
	 * @return
	 */
	@RequestMapping("")
	public String index() {
		return PREFIX + "countTwo.html";
	}

	/**
	 * 产品统计跳转
	 * 
	 * @return
	 */
	@RequestMapping("/platform")
	public String platform() {
		return PREFIX + "count_platform.html";
	}

	/**
	 * 注册统计页面跳转
	 * 
	 * @return
	 */
	@RequestMapping("/register")
	public String register() {
		return PREFIX + "count_register.html";
	}

	/**
	 * 获取数据统计列表，首页数据
	 */
	@RequestMapping(value = "/listcount")
	@ResponseBody
	public Object listcount(@RequestParam(required = false) String beginTime,@RequestParam(required = false) String endTime) {
		List<PageHomeCount> countDataList = countServiceTwo.selectHomePageCount(beginTime, endTime);
		Integer bannerNum = countServiceTwo.getBannerNum();// 获取首页banner的个数时
		CountData cd = new CountData();
		Map<String, Object> map = new HashMap<String, Object>();
		for (PageHomeCount phc : countDataList) {
			if (StringUtil.isNotEmpty(phc)) {
				Integer sum = phc.getSumm();
				Integer home = phc.getHomePageId();
				Integer banner = phc.getBannerId();
				Integer starPlatform = phc.getStarPlatformId();
				Integer button = phc.getButtonId();
				Integer cardPageId = phc.getCardPageId();
				if (StringUtil.isNotEmpty(home)) {
					map.put("homeCount", sum);
				}
				if (StringUtil.isNotEmpty(banner)) {
					map.put("banner" + banner, sum);
				}
				if (StringUtil.isNotEmpty(starPlatform)) {
					map.put("startPlatform" + starPlatform, sum);
				}
				if (StringUtil.isNotEmpty(button)) {
					map.put("button" + button, sum);
				}
				if (StringUtil.isNotEmpty(cardPageId)) {
					map.put("CardPageId" + cardPageId, sum);
				}
			}
		}
		map.put("bannerNum", bannerNum);// 将首页banner的个数传到管理页面
		return map;
	}

	/**
	 * 获取数据统计列表，首页数据
	 */
	@RequestMapping(value = "/loginListcount")
	@ResponseBody
	public Object loginListcount(@RequestParam(required = false) String beginTime,@RequestParam(required = false) String endTime) {
		List<PageHomeCount> countDataList = countServiceTwo.selectHomePageLoginCount(beginTime, endTime);
		Integer bannerNum = countServiceTwo.getBannerNum();// 获取首页banner的个数时
		CountData cd = new CountData();
		Map<String, Object> map = new HashMap<String, Object>();
		for (PageHomeCount phc : countDataList) {
			if (StringUtil.isNotEmpty(phc)) {
				Integer sum = phc.getSumm();
				Integer home = phc.getHomePageId();
				Integer banner = phc.getBannerId();
				Integer starPlatform = phc.getStarPlatformId();
				Integer button = phc.getButtonId();
				Integer cardPageId = phc.getCardPageId();
				if (StringUtil.isNotEmpty(home)) {
					map.put("userhomeCount", sum);
				}
				if (StringUtil.isNotEmpty(banner)) {
					map.put("userbanner" + banner, sum);
				}
				if (StringUtil.isNotEmpty(starPlatform)) {
					map.put("userstartPlatform" + starPlatform, sum);
				}
				if (StringUtil.isNotEmpty(button)) {
					map.put("userbutton" + button, sum);
				}
				if (StringUtil.isNotEmpty(cardPageId)) {
					map.put("userCardPageId" + cardPageId, sum);
				}
			}
		}
		map.put("loginBannerNum", bannerNum);// 将首页banner的个数传到管理页面
		return map;
	}


	/**
	 * 产品统计列表
	 * 
	 * @param beginTime
	 * @param endTime
	 * @return
	 */
	// @RequestMapping(value = "/platformCount")
	// @ResponseBody
	// public Object selectPlatformCount(@RequestParam(required = false) String beginTime,
	// @RequestParam(required = false) String endTime) {
	// Page<PlatFormCount> page = new PageFactory<PlatFormCount>().defaultPage();
	// List<PlatFormCount> pcList = makePCList(beginTime, endTime);
	// page.setRecords(pcList);
	// return super.packForBT(page);
	//
	// }
	/**
	 * 分页产品统计列表
	 * 
	 * @param beginTime
	 * @param endTime
	 * @return
	 */
	@RequestMapping(value = "/platformCount")
	@ResponseBody
	public Object selectPlatformCount(@RequestParam(required = false) String beginTime,@RequestParam(required = false) String endTime) {
		Page<PlatFormCount> page = new PageFactory<PlatFormCount>().defaultPage();
		// List<PlatFormCount> pcList = makePCList(beginTime, endTime);
		List<PlatFormCount> pfcList = countServiceTwo.selectPageListByQueryGetMap(page, beginTime, endTime);
		List<PlatFormCount> pcList = new ArrayList<PlatFormCount>();
		Integer num = 1;
		for (PlatFormCount pfc : pfcList) {
			if (StringUtil.isNotEmpty(pfc)) {
				if (StringUtil.isNotEmpty(pfc.getAbbreviation())) {
					pfc.setOrderNumber(num);
					pcList.add(pfc);
					num++;
				}
			}
		}
		page.setRecords(pcList);
		return super.packForBT(page);
	}

	/**
	 * 贷款总浏览量
	 * 
	 * @param beginTime
	 * @param endTime
	 * @return
	 */
	@RequestMapping(value = "/totalPlatform")
	@ResponseBody
	public Integer getTotalPlatform(@RequestParam(required = false) String beginTime,@RequestParam(required = false) String endTime) {
		Integer totalPlatform = countServiceTwo.getTotalLoanCount(beginTime, endTime);
		return totalPlatform;
	}

	/**
	 * 注册统计数据列表
	 * 
	 * @param beginTime
	 * @param endTime
	 * @return
	 */
	@RequestMapping(value = "/registerCount")
	@ResponseBody
	public Object selectRegisterCount(@RequestParam(required = false) String beginTime,@RequestParam(required = false) String endTime) {
		Page<RegisterCount> page = new PageFactory<RegisterCount>().defaultPage();
		List<RegisterCount> registerList = countServiceTwo.selectRegisterCount(beginTime, endTime);
		Integer totalRegisterCount = 0;
		Integer totalClickCount = 0;
		Integer num = 1;
		for (RegisterCount rc : registerList) {
			rc.setOrderNumber(num);
			Integer sum = rc.getRegisterCount();
			Integer sumOne = rc.getClickCount();
			totalRegisterCount += sum;
			totalClickCount += sumOne;
			num++;
		}
		for (RegisterCount rc : registerList) {
			if (totalRegisterCount != 0) {
				double percent = rc.getRegisterCount() / totalRegisterCount;
				double percentOne = percent * 100;
				DecimalFormat df = new DecimalFormat("#.00");
				String percentTwo = df.format(percent);
				String proportion = percentTwo + "%";
				rc.setProportion(proportion);
			}
		}
		RegisterCount register = new RegisterCount();
		register.setChannelName("合计");
		register.setRegisterCount(totalRegisterCount);
		register.setClickCount(totalClickCount);
		registerList.add(register);
		page.setRecords(registerList);
		return super.packForBT(page);
	}

	/**
	 * 注册总量
	 * 
	 * @param beginTime
	 * @param endTime
	 * @return
	 */
	@RequestMapping(value = "/totalRegister")
	@ResponseBody
	public Integer getTotalRegister(@RequestParam(required = false) String beginTime,@RequestParam(required = false) String endTime) {
		Integer totalRegister = countServiceTwo.getTotalRegister(beginTime, endTime);
		return totalRegister;
	}

	/**
	 * 获取平台统计列表集合
	 * 
	 * @param beginTime
	 * @param endTime
	 * @return
	 */
	public List<PlatFormCount> makePCList(String beginTime, String endTime) {
		List<PlatFormCount> pfcList = countServiceTwo.selectPlatformCount(beginTime, endTime);
		Integer num = 1;
		List<PlatFormCount> pcList = new ArrayList<PlatFormCount>();
		for (PlatFormCount pfc : pfcList) {
			if (StringUtil.isNotEmpty(pfc)) {
				if (StringUtil.isNotEmpty(pfc.getAbbreviation())) {
					pfc.setOrderNumber(num);
					pcList.add(pfc);
					num++;
				}
			}
		}
		return pcList;
	}

	/**
	 * 导出excel表
	 * 
	 * @param beginTime
	 * @param endTime
	 * @param response
	 */
	@RequestMapping(value = "/downloadExcel")
	public void downloadChannelStatisticExcel(@RequestParam(required = false) String beginTime,@RequestParam(required = false) String endTime,
											  HttpServletResponse response) {
		try {
			List<PlatFormCount> pcList = makePCList(beginTime, endTime);
			// 解析成excel文件
			// 第一步，创建一个webbook，对应一个Excel文件
			HSSFWorkbook wb = new HSSFWorkbook();
			// 第二步，在wb中添加一个sheet,对应Excel文件中的sheet
			HSSFSheet sheet = wb.createSheet("点击量数据统计");
			for (int i = 0; i < 6; i++) {
				sheet.setColumnWidth(i, 24 * 256);
			}
			// 第三步，在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
			HSSFRow row = sheet.createRow(0);
			// 第四步，创建单元格，并设置值表头 设置表头居中
			HSSFCellStyle style = wb.createCellStyle();
			style.setAlignment(HorizontalAlignment.CENTER);// 创建一个居中格式
			HSSFCell cell = row.createCell(0);
			cell.setCellValue("序号");
			cell.setCellStyle(style);
			cell = row.createCell(1);
			cell.setCellValue("简称");
			cell.setCellStyle(style);
			cell = row.createCell(2);
			cell.setCellValue("浏览量");
			cell.setCellStyle(style);
			cell = row.createCell(3);
			cell.setCellValue("点击申请量");
			cell.setCellStyle(style);
			// 填充数据
			for (int i = 0; i < pcList.size(); i++) {
				PlatFormCount map = pcList.get(i);
				row = sheet.createRow(i + 1);
				Integer orderNumber = map.getOrderNumber();
				String name = map.getAbbreviation();
				if (StringUtil.isEmpty(name)) {
					name = "暂无";
				}
				Integer visitCount = map.getVisitCount();
				Integer clickCount = map.getClickCount();
				// 第四步，创建单元格，并设置值
				for (int j = 0; j <= 3; j++) {
					row.createCell(j).setCellStyle(style);
				}
				row.getCell(0).setCellValue(orderNumber);
				row.getCell(1).setCellValue(name);
				row.getCell(2).setCellValue(visitCount);
				row.getCell(3).setCellValue(clickCount);
			}
			String date = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
			String filename = "data" + date + ".xls";
			response.setHeader("Content-Disposition","attachment; filename=\"" + URLEncoder.encode(filename, "UTF-8") + "\"");
			response.setContentType("application/octet-stream;charset=UTF-8");
			OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
			wb.write(outputStream);
			outputStream.flush();
			outputStream.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}